package com.bsoft.gol.hcs.his.service.impl;

import com.bsoft.gol.hcs.clinical.bean.qo.DoctorListQo;
import com.bsoft.gol.hcs.clinical.bean.req.OutpatientDocRequest;
import com.bsoft.gol.hcs.clinical.bean.response.DiagnosticInformationResponse;
import com.bsoft.gol.hcs.clinical.bean.response.PrescriptionInformationResponse;
import com.alibaba.fastjson.JSONObject;
import com.bsoft.gol.hcs.common.bean.request.GetMedicalRecordsReq;
import ctd.controller.exception.ControllerException;
import ctd.spring.boot.annotation.SsdevService;
import ctd.util.annotation.RpcService;
import hcn.base.Organization;
import hcn.util.BaseResponse;
import hcn.util.ResultCode;
import com.bsoft.gol.hcs.his.bean.request.OutpatientListQueryRequest;
import com.bsoft.gol.hcs.his.bean.request.QueryOutpatientListRequest;
import com.bsoft.gol.hcs.his.bean.response.*;
import com.bsoft.gol.hcs.his.service.OutpatientDocService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import service.rpc.impl.OrganizationRpcServiceImpl;
import service.rpc.impl.PcnIdentityServiceImpl;
import com.bsoft.gol.hcs.specialist.dao.FusTeamChronicGroupRecordDAO;
import com.bsoft.gol.hcs.specialist.entity.FusTeamChronicGroupRecordEntity;
import com.bsoft.gol.hcs.utils.CommonUtils;
import com.bsoft.gol.hcs.utils.Constants;
import com.bsoft.gol.hcs.utils.JSONDateUtil;
import org.atag.util.http.KdHttpClientUtil;
import org.atag.dao.model.SimplePageInfo;
import com.bsoft.gol.hcs.visitrecord.dao.VrOutpatientVisitRecordDAO;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 门诊患者对接his接口
 *
 * @author lxy
 * @date 2020/7/18
 */
@SsdevService("outpatientDoc")
public class OutpatientDocServiceImpl implements OutpatientDocService {


    private final static Logger log = LoggerFactory.getLogger(OutpatientDocServiceImpl.class);

    @Autowired
    private FusTeamChronicGroupRecordDAO fusTeamChronicGroupRecordDAO;
    @Autowired
    private VrOutpatientVisitRecordDAO vrOutpatientVisitRecordDAO;

    @Autowired
    private PcnIdentityServiceImpl pcnIdentityServiceImpl;

    @Autowired
    private OrganizationRpcServiceImpl organizationRpcService;

    /**
     * 获取门诊患者列表
     *
     * @param request request
     * @return list
     */
    @Override
    @RpcService
    public OutpatientInfoResponse listPatient(OutpatientListQueryRequest request) throws ControllerException {
        log.info("OutpatientDocServiceImpl.listPatient 入参：{}", request);
        OutpatientInfoResponse response = new OutpatientInfoResponse();
        if (CommonUtils.isNotEmpty(request.getWorkDate())) {
            request.setWorkDate(request.getWorkDate() + " 00:00:00");
        }
        //入参转换开始-zrb
        JSONObject jsonParams = JSONObject.parseObject(JSONObject.toJSONString(request));
        jsonParams.put("organizationId", jsonParams.remove("hospitalCode"));
        jsonParams.put("doctorId", jsonParams.remove("docJobNumber"));
        jsonParams.put("scheduleDate", jsonParams.remove("workDate"));
        //入参转换结束
        JSONObject jsonObject = KdHttpClientUtil.doMainPost(Constants.HIS_CLIENT_URL_01
                + Constants.OUTPATIENT_LIST_PATIENT, jsonParams);
        log.info("OutpatientDocServiceImpl.listPatient 第三方返回数据:{}", jsonObject);
        try {
            if (jsonObject.getInteger("code") == Constants.SUCCESS_CODE && jsonObject.containsKey("data") &&
                    jsonObject.get("data") != null) {
                StatisticalInfo statisticalInfo = JSONObject.parseObject(
                        jsonObject.get("data").toString(), StatisticalInfo.class);
                JSONObject data = JSONObject.parseObject(jsonObject.get("data").toString());
                List<PatientTemporary> patientTemporaryList = JSONObject.parseArray(
                        data.get("patientList").toString(), PatientTemporary.class);
                List<Patient> patientList = new ArrayList<>();
                response.setStatisticalInfo(statisticalInfo);
                for (PatientTemporary temporary : patientTemporaryList) {
                    Patient patient = new Patient();
                    BeanUtils.copyProperties(temporary, patient);
                    patient.setHospitalCode(temporary.getOrganizationId());
                    patient.setHospitalName(temporary.getOrganizationName());
                    patient.setEmergencyNumber(temporary.getAdmNumber());
                    patient.setPatientCode(temporary.getPatientId());
                    patientList.add(patient);
                }
                response.setPatientList(patientList);
            } else {
                throw new ControllerException(jsonObject.getString("message"));
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new ControllerException(Constants.JSON_ANALYSIS_ERR + e.getMessage());
        }
        log.info("OutpatientDocServiceImpl.listPatient 出参：{}", response);
        return response;
    }

    /**
     * 同步就医记录
     *
     * @param recordsReq
     * @return
     */
    @Override
    @RpcService
    public List<GetMedicalRecordsResp> getMedicalRecords(GetMedicalRecordsReq recordsReq) throws ControllerException {
        log.info("OutpatientDocServiceImpl.getMedicalRecords 入参：{}", recordsReq);
        List<GetMedicalRecordsResp> medicalRecordsResp = new ArrayList<>();
        JSONObject jsonParams = JSONObject.parseObject(JSONObject.toJSONString(recordsReq));
        JSONObject jsonObject = KdHttpClientUtil.doPostJSONRequest(Constants.HIS_CLIENT_URL_01 + Constants.GET_RECORDS, jsonParams);
        log.info("OutpatientDocServiceImpl.listHistoryRecord 第三方返回数据:{}", jsonObject);
        try {
            if (jsonObject.getInteger("code") == ResultCode.SUCCESS && jsonObject.containsKey("data") &&
                    jsonObject.get("data") != null) {
                medicalRecordsResp = JSONObject.parseArray(
                        jsonObject.get("data").toString(), GetMedicalRecordsResp.class);
                if (CommonUtils.isNotEmpty(medicalRecordsResp)) {
                }
            } else {
                throw new ControllerException(jsonObject.getString("message"));
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new ControllerException(Constants.JSON_ANALYSIS_ERR + e.getMessage());
        }
        log.info("OutpatientDocServiceImpl.getMedicalRecords 出参：{}", medicalRecordsResp);
        return medicalRecordsResp;
    }

    /**
     * 获取门诊患者列表(7/28列表改造-最新)
     *
     * @param request
     * @return
     */
    @Override
    @RpcService
    public QueryOutpatientListResponse queryOutpatientList(QueryOutpatientListRequest request) throws ControllerException {
        log.info("OutpatientDocServiceImpl.queryOutpatientList 入参：{}", JSONObject.toJSON(request));
        QueryOutpatientListResponse response = new QueryOutpatientListResponse();
        JSONObject jsonParams = JSONObject.parseObject(JSONObject.toJSONString(request));
//        String testUrl = "http://interfacedemo.zk.atag.bsoft.com.cn/outpatient/listPatient";
//        //JSONObject jsonObject = HttpClientUtils.doPostJSONRequest(Constants.HIS_CLIENT_URL_01 + Constants.OUTPATIENT_LIST_PATIENT, jsonParams);
//        JSONObject jsonObject = HttpClientUtils.doPostJSONRequest(testUrl, jsonParams);
        String jsonContext = JSONDateUtil.readFile("queryOutpatientList");
        JSONObject jsonObject = JSONObject.parseObject(jsonContext);
//                List<PatientInfo> patientInfoList =  JSONArray.parseArray(jsonContext, PatientInfo.class);
        log.info("OutpatientDocServiceImpl.queryOutpatientList 第三方返回数据:{}", JSONObject.toJSONString(jsonObject));
        try {
            if (jsonObject.getInteger("code") == ResultCode.SUCCESS && jsonObject.containsKey("data") && jsonObject.get("data") != null) {
                response = JSONObject.parseObject(jsonObject.get("data").toString(), QueryOutpatientListResponse.class);
                List<PatientInfo> patientInfoList = response.getPatientList();
                if (patientInfoList != null && patientInfoList.size() > 0) {
                    for (PatientInfo patientInfo : patientInfoList) {
                        String patientId = patientInfo.getPatientId();
                        if (CommonUtils.isNotEmpty(patientId)) {
                            List<FusTeamChronicGroupRecordEntity> fusList = fusTeamChronicGroupRecordDAO.findFusRecordsByPersonId(patientId);
                            if (fusList != null && fusList.size() > 0) {
                                if (fusList.size() == 1) {
                                    patientInfo.setChronicNameCollection(fusList.get(0).getChronicDiseaseName());
                                } else if (fusList.size() > 1) {
                                    String chronicNameCollection = "";
                                    for (FusTeamChronicGroupRecordEntity fusBean : fusList) {
                                        chronicNameCollection += fusBean.getChronicDiseaseName() + ",";
                                    }
                                    chronicNameCollection = chronicNameCollection.substring(0, chronicNameCollection.length() - 1);
                                    patientInfo.setChronicNameCollection(chronicNameCollection);
                                }
                            }

                        }
                    }
                }
                log.info("OutpatientDocServiceImpl.queryOutpatientList 出参：{}", JSONObject.toJSONString(response));
            } else {
                throw new ControllerException(jsonObject.getString("message"));
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new ControllerException(Constants.JSON_ANALYSIS_ERR + e.getMessage());
        }
        return response;
    }

    /**
     * 查询数据库门诊患者列表
     *
     * @param request 列表查询入参
     * @return 门诊分页列表
     */
    @Override
    @RpcService
    public SimplePageInfo<PatientInfo> queryLocalOutpatientList(QueryOutpatientListRequest request) {
        BaseResponse result = new BaseResponse();
        SimplePageInfo<PatientInfo> patientInfoList = vrOutpatientVisitRecordDAO.queryLocalOutpatientList(request);
        if (CommonUtils.isNotEmpty(patientInfoList)) {
            String mpiId = null;
            for (PatientInfo patient : patientInfoList.getList()) {
                if (CommonUtils.isNotEmpty(patient.getVisitOrganization())) {
                    Organization orgDetailByOrgCode = organizationRpcService.getOrgDetailByOrgCode(patient.getVisitOrganization());
                    mpiId = pcnIdentityServiceImpl.findMpiIdByPatientCode(orgDetailByOrgCode.getOrgId(), patient.getPatientId());
                }
                if (CommonUtils.isEmpty(mpiId)) {
                    patient.setPersonId(patient.getPatientId());
                } else {
                    patient.setPersonId(mpiId);
                }
            }
        }
        return patientInfoList;
    }

    @Override
    @RpcService
    public List<Map<String, String>> outPatientDoctorList(DoctorListQo request) {
        List<Map<String, String>> mapList = vrOutpatientVisitRecordDAO.outPatientDoctorList(request.getOrganizationId());
        return mapList;
    }

    @Override
    @RpcService
    public List<MedicalRecordTemplateResponse> getMedicalRecordInformation(OutpatientDocRequest request) {
        return null;
    }

    @Override
    @RpcService
    public List<DiagnosticInformationResponse> getDiagnoseInformation(OutpatientDocRequest request) {
        return null;
    }

    @Override
    @RpcService
    public List<PrescriptionInformationResponse> getPrescriptionInformation(OutpatientDocRequest request) {
        return null;
    }
}
